package com.code.modules.base.controller;


import com.code.common.utils.JWTUtil;
import com.code.common.vo.ResultData;
import com.code.config.Swagger.params.ApiJsonObject;
import com.code.config.Swagger.params.ApiJsonProperty;
import com.code.modules.base.model.User;
import com.code.modules.base.service.UserService;
import com.code.modules.base.vo.LoginVo;
import com.code.modules.base.vo.UserinfoVo;
import io.swagger.annotations.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

@RestController
@Api(value = "登录控制器", tags = {"登录接口"})
public class LoginController {

    @Autowired
    private UserService userService;

    @ApiOperation("用户登录,登录成功获得jwttoken,[在header中token:jwttoken]")
    @PostMapping("/login")
    public ResultData login(@RequestBody LoginVo loginvo) {
        boolean flag = userService.checkUser(loginvo.getUsername(),loginvo.getPassword());
        if(flag == true) {
            User user = userService.findUserByusername(loginvo.getUsername());
            String jwt = JWTUtil.getJwtToken(loginvo.getUsername());
            UserinfoVo uinfo = new UserinfoVo();
            uinfo.setId(user.getId());
            uinfo.setUsername(user.getUsername());
            uinfo.setAvatar(user.getAvatar_url());
            uinfo.setJwt(jwt);
            uinfo.setWithexpiresAt(JWTUtil.getjwtExpiration(jwt));
            return  new ResultData().succ(200,"用户登录成功",uinfo);
        }
        return  new ResultData().fail(400,"用户或密码错误");
    }


    @ApiOperation("校验token是否过期,传入JSON.stringify({jwttoken:token})")
    @PostMapping("/checktoken")
    public ResultData checktoken(@ApiJsonObject(name = "checktoken_Map", value = {
            @ApiJsonProperty(key = "jwttoken",  example = "token",  description = "检验token", type = String.class, required = true) })
            @RequestBody Map<String,Object> params) {
        String jwttoken = (String) params.get("jwttoken");
        if(jwttoken != "") {
            Date claimDate =  JWTUtil.getDateByToken(jwttoken);
            if(claimDate != null) {
                boolean flag =  JWTUtil.isTokenExpired(claimDate);
                if(flag != true) {
                    return  new ResultData().succ(200,"token有效",true);
                }
            }
        }
        return  new ResultData().fail(400,"token已失效",false);
    }


    @ApiOperation("用户注销，必须带有token")
    @RequiresAuthentication
    @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", dataType = "String", name = "token", value = "token", required = true) })
    @GetMapping("/logout")
    public ResultData logout() {
        SecurityUtils.getSubject().logout();
        return new ResultData().succ(200,"用户退出");
    }



    //@ApiOperation("统一报错错误接口")
//    @RequestMapping(path = "/unauthorized/{message}",method = {RequestMethod.GET,RequestMethod.POST}, produces="application/json")
//    public ResultData unauthorized(@PathVariable("message") String message) throws UnsupportedEncodingException {
//        int code = 4000;
//        System.out.println("--unauthorized---msg"+message);
//        return new ResultData().succ(code,message,null);
//    }



}
